﻿using System.DirectoryServices.Protocols;
using AutoMapper;
using B.S.Production.Domain.Entities;
using B.S.Production.ErrorCode;
using B.S.Production.Read.API.Application.Command.GetProductionOrderCommand;
using B.S.Production.Read.API.Dto;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;

namespace B.S.Production.Read.API.Application.CommandHandler.GetProductionOrderCommandHandler
{
    public class ShowProductionOrderCommandHandler : IRequestHandler<ShowProductionOrderCommand, ApiPaging<ProductionOrderDTO>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public ShowProductionOrderCommandHandler(ISqlSugarClient db,IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public Task<ApiPaging<ProductionOrderDTO>> Handle(ShowProductionOrderCommand request, CancellationToken cancellationToken)
        {
           ApiPaging<ProductionOrderDTO> result = new ApiPaging<ProductionOrderDTO>();
            var list = db.Queryable<ProductionOrder>();
            //if (request.StartDate!=null)
            //{
            //    list = list.Where(x => x.StartDate == request.StartDate);
            //}

            //if (request.EndDate !=null)
            //{
            //    list = list.Where(x => x.EndDate == request.EndDate);
            //}
            if (request.ProductNumber>0)
            {
                list = list.Where(x=>x.ProductNumber == request.ProductNumber);
            }
            //总条数
            var totalCount = list.Count();
            //总页数
            var pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            //分页显示
            list = list.OrderByDescending(a => a.ProdunctionId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            result.TotalCount = totalCount;
            result.TotalPage = pageCount;
            result.Items = mapper.Map<List<ProductionOrderDTO>>(list.ToList());

                result.Code = ApiEnums.查询成功;
                result.Msg = ApiEnums.查询成功.ToString();
            

            return Task.FromResult(result);
        }
    }
}
